package demo.android.ipc;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.google.gson.Gson;
import com.hss01248.facedetect.BaseURL;
import com.hss01248.facedetect.activity.FaceTrackActivity;
import com.hss01248.facedetect.utils.FloatViewService;
import com.hss01248.facedetect.utils.SpeechUtils;
import com.hss01248.facedetect.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.hss01248.facedetect.BaseURL.URL_UNBINDPHONELIST;

public class ChoiceActivity extends AppCompatActivity {

    private LinearLayout ll_collect;
    private LinearLayout ll_qrcode;
    private LinearLayout ll_face;
    private ImageView Img_menu;
    private long exitTime;


    /**********************语音合成**********************/
//语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                Log.i(TAG, "onInit: TTS引擎初始化成功");
            } else{
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }

    private static final String TAG = "PhoneActivity";
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed=1.0f;   //合成语音的语速
    private static float m_voice_pitch=1.0f;   //合成语音的语调
    /****************************************************/

    private PopupWindow popupWindow;
    private int screenWidth, screenHeight;
    ArrayList arrayList;
    List<GateListResponse.GateInfoListBean> list;

    SharedPreferences sp;
    SharedPreferences.Editor edit;
    GateListResponse gateListResponse;
    View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE); // 去掉标题栏 有效
        setContentView(R.layout.activity_choice);


        mSpeech = new TextToSpeech(ChoiceActivity.this, new TTSListener());


//        动态请求camera权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[] {Manifest.permission.CAMERA}, 1);
            }
        }

        //        SharedPreferences初始化，以及变量获取
        sp = getSharedPreferences("position", Context.MODE_PRIVATE);
        edit = sp.edit();

        //        获取手机屏幕大小，为弹窗提供参数
        WindowManager manager = (WindowManager) getBaseContext().getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        Point point = new Point();
        if (Build.VERSION.SDK_INT < 17) {
            display.getSize(point);
        } else {
            display.getRealSize(point);
        }
        screenWidth = point.x;
        screenHeight = point.y;

        ll_face = (LinearLayout) findViewById(R.id.ca_ll_face);
        ll_qrcode = (LinearLayout) findViewById(R.id.ca_ll_qrcode);
        ll_collect = (LinearLayout) findViewById(R.id.ca_ll_collect);
        Img_menu = (ImageView) findViewById(R.id.img_menu);
        ll_face.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity( new Intent(ChoiceActivity.this, FaceTrackActivity.class));
            }
        });
        ll_qrcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ChoiceActivity.this,MainActivity.class));
            }
        });
        ll_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ChoiceActivity.this,OptionActivity.class));
            }
        });


        Img_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view = View.inflate(ChoiceActivity.this, R.layout.popupwindow_ma_layout, null); //引入布局
                //获取PopupWindow中View的宽高
                view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

                //将布局view传参给popupwindow
                popupWindow = new PopupWindow(view, screenWidth, screenHeight * 3 / 5);
                popupWindow.setBackgroundDrawable(new ColorDrawable(0xaa000000));//设置背景

                popupWindow.setFocusable(true);//popupwindow设置焦点
                popupWindow.setOutsideTouchable(true);//点击外面窗口消失
                popupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

                setOnPopupViewClick(view);
                popupWindow.setAnimationStyle(android.R.style.Animation_Translucent);//设置动画
            }
        });


//
//        try {
//            getGateList();
//        } catch (Exception e) {
//            ToastUtil.showToast(e.getMessage());
//        }

    }

    @Override
    protected void onResume() {
        super.onResume();
//        //初始化TTS引擎
//        if (mSpeech==null) {
//
//            mSpeech = new TextToSpeech(ChoiceActivity.this, new TTSListener());
//        }


    }

    //播放合成语音
    public void PlayAudioFile(String str)
    {
        //设置中文
        int supported = mSpeech.setLanguage(Locale.CHINA);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)){
            //语言设置失败
            Log.i(TAG, "中文设置失败");
        }
        else{
            Log.i(TAG, "中文设置成功");
        }
        //mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        mSpeech.speak(str,TextToSpeech.QUEUE_ADD,null);
    }

    private void setOnPopupViewClick(View view) {

        final ImageView img_close = (ImageView) view.findViewById(R.id.pop_img_close);
        final ListView pop_list = (ListView) view.findViewById(R.id.pop_list);
        final PopListAdapter adapter;
        if (list != null && list.size() > 0) {
            adapter = new PopListAdapter(getBaseContext(), list);
            pop_list.setAdapter(adapter);
        } else {
            ToastUtil.showToast("闸机列表为空，请检查IP设置");
            return;
        }

        img_close.getRootView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                ToastUtil.showToast("关闭弹窗");
            }
        });
        pop_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                edit.putInt("position", position);
//                edit.putString("gateName", list.get(position).getGateName());
                edit.putString("gateNo", list.get(position).getGateNo());

                edit.commit();

                adapter.notifyDataSetChanged();
                ToastUtil.showToast("选中 " + list.get(position).getGateNo() + " 成功");
            }
        });
    }

    private void getGateList() {
//        清空缓存，用于及时更新数据
        if (list != null) {
            list = null;
        }

        String url = URL_UNBINDPHONELIST;


        OkHttpUtils
                .get()
                .url(url)
                .addParams("userName", "admin")
                .addParams("password", "888888")
                .addParams("sign", "DDCA01EF3FF8B6C429D8FE406740539F")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtil.showToast("获取闸机列表失败，请检查ip设置");
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        try {
                            gateListResponse = new Gson().fromJson(response, GateListResponse.class);
                            if (gateListResponse.getCode().equals("0")) {

                                list = gateListResponse.getGateInfoList();

                            } else {
                                ToastUtil.showToast("" + gateListResponse.getMessage());
                            }
                        } catch (Exception e) {
                            ToastUtil.showToast("获取闸机列表失败");

                        }
                    }

                });

//         url = URL_UNBINDPHONELIST;
//        Map<String, String> params = new HashMap<>();
//        params.put("name", "tsy");
//        params.put("age", "24");
//        OkHttpClient okHttpClient = new OkHttpClient();
//        final Request request = new Request.Builder()
//                .url(url+"?userName=admin&password==888888&sign=DDCA01EF3FF8B6C429D8FE406740539F")
//
//                .get()//默认就是GET请求，可以不写
//                .build();
//        Call call = okHttpClient.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: ");
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, "onResponse: " + response.body().string());
//            }
//        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mSpeech!=null) {
            mSpeech.shutdown();
        }
    }

    @Override
    protected void onStart() {

//        Intent intent = new Intent(ChoiceActivity.this, FloatViewService.class);
//        //启动FloatViewService
//        startService(intent);
        super.onStart();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                ToastUtil.showToast("再次点击，退出应用");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
